<?php

namespace app\agent\controller;

use think\facade\Db;

class Qrcode extends Base
{
    /**
     * 获取列表
     */
    public function getList()
    {
        $shop_id = input('shop_id', 0, 'intval');
        $page = input('page', 1, 'intval');
        $pagesize = input('pagesize', 10, 'intval');
        $page = max(1, $page);
        $pagesize = max(1, $pagesize);

        // 查询列表
        $where = [
            ['agent_id', '=', self::$agent['id']],
            ['shop_id', '=', $shop_id]
        ];
        $list = Db::name('qrcode')
            ->where($where)
            ->field('id,shop_id,title,speaker_status,FROM_UNIXTIME(add_time, \'%Y-%m-%d %H:%i\') as add_time')
            ->page($page, $pagesize)
            ->select()->each(function ($item) {
                $item['qrcode'] = mediaUrl('/upload/qrcode/qrcode_' . $item['id'] . '.png');
                $file_merge = '/upload/qrcode/merge/qrcode_' . $item['id'] . '.png';
                if(file_exists('.' . $file_merge)) {
                    $item['qrcode_merge'] = mediaUrl($file_merge);
                } else {
                    $item['qrcode_merge'] = $item['qrcode'];
                }
                return $item;
            });
        $count = Db::name('qrcode')
            ->where($where)
            ->count();

        return successJson([
            'count' => $count,
            'list' => $list
        ]);
    }

    /**
     * 取单个资料
     */
    public function getInfo()
    {
        $id = input('id', 0, 'intval');

        $info = Db::name('qrcode')
            ->where([
                ['agent_id', '=', self::$agent['id']],
                ['id', '=', $id]
            ])
            ->field('id,title,speaker_status,speaker_brand,speaker_config')
            ->find();
        if($info['speaker_config']) {
            $config = json_decode($info['speaker_config'], true);
            if($info['speaker_brand'] == 'pinsheng') {
                $info['speaker_devid'] = $config['devid'];
            }
            unset($info['speaker_config']);
        }

        if (!$info) {
            return errorJson('没有找到数据，请刷新页面重试');
        }

        return successJson($info);
    }

    /**
     * 更新或新增
     */
    public function saveInfo()
    {
        $id = input('id', 0, 'intval');
        $shop_id = input('shop_id', 0, 'intval');
        $title = input('title', '', 'trim');
        $speaker_status = input('speaker_status', '', 'trim');
        $speaker_brand = input('speaker_brand', '', 'trim');
        if (empty($title)) {
            return errorJson('名称不能为空');
        }
        $shop = Db::name('shop')
            ->where([
                ['agent_id', '=', self::$agent['id']],
                ['id', '=', $shop_id]
            ])
            ->find();
        if (!$shop) {
            return errorJson('商户不存在，请刷新页面重试');
        }

        $data = [];
        $data['title'] = $title;
        $data['speaker_status'] = $speaker_status;
        $data['speaker_brand'] = $speaker_brand;
        if ($speaker_status) {
            $speaker = [];
            if ($speaker_brand == 'pinsheng') {
                $speaker['devid'] = input('speaker_devid', '', 'trim');
            }
            $data['speaker_config'] = json_encode($speaker);
        }

        // 更新或添加
        if ($id) {
            $res = Db::name('qrcode')
                ->where([
                    ['shop_id', '=', $shop_id],
                    ['id', '=', $id]
                ])
                ->update($data);
        } else {
            $now = time();
            $data['agent_id'] = $shop['agent_id'];
            $data['shop_id'] = $shop_id;
            $data['bind_time'] = $now;
            $data['add_time'] = $now;
            $res = Db::name('qrcode')->insert($data);
            $id = Db::name('qrcode')->getLastInsID();
        }

        if ($res !== false) {
            // 重新生成二维码图片
            $dir = 'upload/qrcode';
            if(defined('__PUBLIC__')) {
                $dir = __PUBLIC__ . $dir;
            }
            $code = new \FoxQrcode\code($dir);
            $url = mobileUrl('/pay/qrcode/index', ['id' => $id]);
            $filename = 'qrcode_' . $id;
            $size = 40;
            $code->png($url, $filename, $size);
            // 合成带背景图片
            qrcodeMerge('./' . $dir . '/' . $filename . '.png', $id);
            return successJson('', '保存成功');
        } else {
            return errorJson('保存失败，请重试！');
        }

    }

    /**
     * 删除
     */
    public function del()
    {
        return errorJson('非法操作');
        $id = input('id', 0, 'intval');
        $res = Db::name('qrcode')
            ->where([
                ['agent_id', '=', self::$agent['id']],
                ['id', '=', $id]
            ])
            ->delete();
        if ($res !== false) {
            return successJson('', '删除成功');
        } else {
            return errorJson('删除失败，请重试！');
        }
    }

    /**
     * 测试音箱配置
     */
    public function speakerTest()
    {
        $brand = input('speaker_brand', '', 'trim');
        if($brand == 'pinsheng') {
            $devid = input('speaker_devid', '', 'trim');
            $setting = getSystemSetting('speaker');
            if(empty($setting['pinsheng_username']) || empty($setting['pinsheng_password'])) {
                return errorJson('请先完善系统配置中的收款音箱配置');
            }
            $speaker = new \Speaker\pinsheng\sdk($setting['pinsheng_username'], $setting['pinsheng_password']);
            $result = $speaker->play($devid,'alipay', 0.01);
            if ($result === true) {
                return successJson('', '播放命令已发送');
            } else {
                return errorJson('命令发送失败：' . $result['message']);
            }
        }

        return errorJson('暂不支持');
    }

    /**
     * 下载二维码
     */
    public function qrcodeDownload()
    {
        $id = input('id', 0, 'intval');
        $shop_id = input('shop_id', 0, 'intval');
        $qrcode = Db::name('qrcode')
            ->where([
                ['agent_id', '=', self::$agent['id']],
                ['id', '=', $id]
            ])
            ->field('title')
            ->find();
        if(!$qrcode) {
            return errorJson('二维码不存在');
        }

        $filename = 'upload/qrcode/qrcode_' . $shop_id . '_' . $id . '.png';
        if (!file_exists($filename)) {
            return errorJson('图片不存在');
        }
        //设置头信息
        header('Content-Disposition:attachment;filename=' . $qrcode['title'] . '.png');
        header('Content-Length:' . filesize($filename));
        //读取文件并写入到输出缓冲
        echo file_get_contents($filename);
        exit;
    }



    /**
     * 获取列表
     */
    public function getBatchList()
    {
        $page = input('page', 1, 'intval');
        $pagesize = input('pagesize', 10, 'intval');
        $page = max(1, $page);
        $pagesize = max(1, $pagesize);
        $keyword = input('keyword', '', 'trim');

        $where = [
            ['agent_id', '=', self::$agent['id']]
        ];
        if ($keyword) {
            $where[] = ['remark', 'like', '%' . $keyword . '%'];
        };

        // 查询列表
        $list = Db::name('qrcode_batch')
            ->where($where)
            ->field('id,num,remark,add_time')
            ->page($page, $pagesize)
            ->order('id desc')
            ->select()->each(function ($item) {
                $item['add_time'] = date('Y-m-d H:i', $item['add_time']);
                $item['used'] = Db::name('qrcode')
                    ->where([
                        ['batch_id', '=', $item['id']],
                        ['shop_id', '>', 0]
                    ])
                    ->count();
                return $item;
            });
        $count = Db::name('qrcode_batch')
            ->where($where)
            ->count();

        return successJson([
            'count' => $count,
            'list' => $list
        ]);
    }

    public function createBatch()
    {
        $now = time();
        $num = input('num', 0, 'intval');
        $remark = input('remark', '', 'trim');

        if ($num <= 0) {
            return errorJson('请输入数量');
        }
        if ($num > 100) {
            return errorJson('每次最多生成100张');
        }
        // 创建批次
        Db::startTrans();
        try {
            $batch_id = Db::name('qrcode_batch')
                ->insertGetId([
                    'agent_id' => self::$agent['id'],
                    'num' => $num,
                    'remark' => $remark,
                    'add_time' => $now
                ]);
            // 循环生成图片
            $dir = 'upload/qrcode';
            if (defined('__PUBLIC__')) {
                $dir = __PUBLIC__ . $dir;
            }
            $Code = new \FoxQrcode\code($dir);

            for ($i = 0; $i < $num; $i++) {
                $qrcode_id = Db::name('qrcode')
                    ->insertGetId([
                        'agent_id' => self::$agent['id'],
                        'batch_id' => $batch_id,
                        'add_time' => $now
                    ]);
                // 生成图片
                $url = mobileUrl('/pay/qrcode/index', ['id' => $qrcode_id]);
                $filename = 'qrcode_' . $qrcode_id;
                $size = 40;
                $Code->png($url, $filename, $size);
                // 合成带背景图片
                qrcodeMerge('./' . $dir . '/' . $filename . '.png', $qrcode_id);
            }

            Db::commit();
            return successJson('', '创建成功');

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return errorJson('创建失败，请重试！' . $e->getMessage());
        }
    }

    /**
     * 删除
     */
    public function batchDel()
    {
        return errorJson('非法操作');
        $id = input('id', 0, 'intval');
        $used = Db::name('qrcode')
            ->where([
                ['agent_id', '=', self::$agent['id']],
                ['batch_id', '=', $id],
                ['shop_id', '>', 0]
            ])
            ->count();
        if ($used > 0) {
            return errorJson('请先将已绑定的收款码解绑');
        }
        // 开启删除事务
        Db::startTrans();
        try {
            Db::name('qrcode')
                ->where([
                    ['agent_id', '=', self::$agent['id']],
                    ['batch_id', '=', $id]
                ])
                ->delete();
            Db::name('qrcode_batch')
                ->where([
                    ['agent_id', '=', self::$agent['id']],
                    ['id', '=', $id]
                ])
                ->delete();
            Db::commit();
            return successJson('', '删除成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return errorJson('删除失败，请重试！');
        }
    }

    /**
     * 获取批次的二维码列表
     */
    public function getBatchQrcode()
    {
        $batch_id = input('batch_id', 0, 'intval');
        $page = input('page', 1, 'intval');
        $pagesize = input('pagesize', 10, 'intval');
        $page = max(1, $page);
        $pagesize = max(1, $pagesize);

        // 查询列表
        $list = Db::name('qrcode')
            ->where([
                ['agent_id', '=', self::$agent['id']],
                ['batch_id', '=', $batch_id]
            ])
            ->field('id,shop_id,title')
            ->page($page, $pagesize)
            ->select()->each(function ($item) {
                $item['qrcode'] = mediaUrl('/upload/qrcode/qrcode_' . $item['id'] . '.png');
                $file_merge = '/upload/qrcode/merge/qrcode_' . $item['id'] . '.png';
                if(file_exists('.' . $file_merge)) {
                    $item['qrcode_merge'] = mediaUrl($file_merge);
                } else {
                    $item['qrcode_merge'] = $item['qrcode'];
                }
                if ($item['shop_id']) {
                    $item['shop_title'] = Db::name('shop')->where('id', $item['shop_id'])->value('title');
                } else {
                    $item['shop_title'] = '-';
                }
                return $item;
            });
        $count = Db::name('qrcode')
            ->where([
                ['agent_id', '=', self::$agent['id']],
                ['batch_id', '=', $batch_id]
            ])
            ->count();

        return successJson([
            'count' => $count,
            'list' => $list
        ]);
    }

    /**
     * 解绑
     */
    public function unbind()
    {
        return errorJson('非法操作');
        $id = input('id', 0, 'intval');
        $rs = Db::name('qrcode')
            ->where([
                ['agent_id', '=', self::$agent['id']],
                ['id', '=', $id]
            ])
            ->update([
                'shop_id' => 0,
                'title' => '',
                'speaker_status' => 0,
                'speaker_brand' => '',
                'speaker_config' => ''
            ]);
        if ($rs !== false) {
            return successJson('', '解绑成功');
        } else {
            return errorJson('解绑失败，请重试！');
        }
    }

    public function getBatchZip()
    {
        $batch_id = input('batch_id', 0, 'intval');
        $unbind = input('unbind', 0, 'intval');
        $where = [
            ['agent_id', '=', self::$agent['id']],
            ['batch_id', '=', $batch_id]
        ];
        if ($unbind) {
            $where[] = ['shop_id', '=', 0];
        }
        $list = Db::name('qrcode')
            ->where($where)
            ->field('id')
            ->column('id');
        try {
            $zipName = './upload/' . uniqid() . '.zip';
            if (!is_file($zipName)) {
                $fp = fopen($zipName, 'w');
                fclose($fp);
            }
            $zip = new \ZipArchive();
            $zip->open($zipName, \ZipArchive::OVERWRITE);
            foreach ($list as $id) {
                $file = './upload/qrcode/qrcode_' . $id . '.png';
                if(is_file($file)) {
                    $zip->addFile($file, basename($file));
                }
                $file_merge = './upload/qrcode/merge/qrcode_' . $id . '.png';
                if(is_file($file_merge)) {
                    $zip->addFile($file_merge, 'merge/' . basename($file_merge));
                }
            }
            $zip->close();
        } catch (\Exception $e) {
            return errorJson('打包失败，请重试');
        }

        if(is_file($zipName)) {
            return successJson([
                'url' => mediaUrl($zipName, true)
            ]);
        } else {
            return errorJson('打包失败，请检查二维码图片是否正常');
        }
    }
}
